package com.seeway.wms.network.utils

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.*

/***
 * @author 86153
 * 验签工具类
 */
object ApiSignUtils {
    const val APP_PLATE_KEY = "125ad075ef3567b461c88b142ce3438d"
    const val APP_SECRET = "eb10d593471be005c110b6b672f7ee06"

    /***
     * & 拼接参数
     * @param params
     * @return
     */
    private fun createLinkString(params: Map<String, String>): String {
        val keys: List<String> =
            ArrayList(params.keys)
        Collections.sort(keys)
        var preStr = ""
        for (i in keys.indices) {
            val key = keys[i]
            val value = params[key]
            // 拼接时，不包括最后一个&字符
            preStr = if (i == keys.size - 1) {
                "$preStr$key=$value"
            } else {
                "$preStr$key=$value&"
            }
        }
        return preStr
    }

    /***
     * 获取签名
     * @param authTime
     * @return
     */
    @JvmStatic
    fun buildSign(authTime: String): String {
        //todo 后端暂时没有算其他参数，所以，参与验签的只有 这两个固定参数
        val newParams =
            HashMap<String, String>(2)
        newParams["authTime"] = authTime
        //平台标识
        newParams["plateKey"] = APP_PLATE_KEY
        //加密sign
        return mD5(
            createLinkString(newParams) + mD5(
                APP_SECRET
            )
        )
    }

    /**
     * MD5加密
     *
     * @param sStr
     * @return String
     */
    private fun mD5(sStr: String): String {
        var sReturnCode = ""
        try {
            val md = MessageDigest.getInstance("MD5")
            md.update(sStr.toByteArray(StandardCharsets.UTF_8))
            val b = md.digest()
            var i: Int
            val sb = StringBuilder("")
            for (value in b) {
                i = value.toInt()
                if (i < 0) {
                    i += 256
                }
                if (i < 16) {
                    sb.append("0")
                }
                sb.append(Integer.toHexString(i))
            }
            sReturnCode = sb.toString()
        } catch (ignored: Exception) {
        }
        return sReturnCode
    }

    private fun sortMapByKey(map: Map<String, Any>?): Map<String, Any>? {
        if (map == null || map.isEmpty()) {
            return null
        }
        val sortMap: MutableMap<String, Any> =
            TreeMap(MapKeyComparator())
        sortMap.putAll(map)
        return sortMap
    }

    private class MapKeyComparator : Comparator<String> {
        override fun compare(str1: String, str2: String): Int {
            return str1.compareTo(str2)
        }
    }
}